﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyCode.Encode
{
        /// <summary>
        ///加密类 
        /// </summary>
        internal class Mycode
        {
            /// <summary>
            ///明文
            /// </summary>
            public string Plaint { get; set; }
            /// <summary>
            ///密文
            /// </summary>
            public string Cipher { get; set; }
            /// <summary>
            //密钥
            /// </summary>
            public string Key { get; set; }
            /// <summary>
            //加密方法
            /// </summary>
            public void ToEncode()
            {
                //ToDo 加密过程
                //得到密钥长度，按长度分配密钥
                int length = Key.Length;
                //转换字符串为数组
                char[] plain = Plaint.ToCharArray();
                char[] key = Key.ToCharArray();
                char[] cipher = new char[Plaint.Length];
                //循环加密计算，将明文分组加密
                for (int i = 0; i < Plaint.Length; i++)
                {
                    //判断小写
                    if (plain[i] >= 'a' && plain[i] <= 'z')
                    //将明文和对应密钥的值相加后，mod26
                    {
                        int temp = (Transform(plain[i]) + Transform(key[i % length])) % 26;
                        //将密文由数值形式变回小写字母，放回数组
                        char ch = Convert.ToChar(temp + 97);
                        cipher[i] = ch;
                    }
                    //判断大写
                    else if (plain[i] >= 'A' && plain[i] <= 'Z')
                    {
                        //将明文和对应密钥的值相加后，mod26
                        int temp = (Transform(plain[i]) + Transform(key[i % length])) % 26;
                        //将密文由数值形式变回大写字母，放回数组
                        char ch = Convert.ToChar(temp + 65);
                        cipher[i] = ch;
                    }
                    //保留空格，逗号，句号
                    else if (plain[i] == ' ')
                    { char ch = Convert.ToChar(' '); cipher[i] = ch; }
                    else if (plain[i] == '.')
                    { char ch = Convert.ToChar('.'); cipher[i] = ch; }
                    else if (plain[i] == ',')
                    { char ch = Convert.ToChar(','); cipher[i] = ch; }
                }
                //返回密文
                Cipher = new string(cipher);
            }
            /// <summary>
            /// 返回指定字符，并赋值0-25的方法
            /// </summary>
            /// <param name="ch"></param>
            /// <returns></returns>
            private int Transform(char ch)
            {
                //小写字母的转化
                if (ch >= 'a' && ch <= 'z')
                    return (ch - 'a');
                //大写字母的转化
                else if (ch >= 'A' && ch <= 'Z')
                    return (ch - 'A');
                else return 0;
            }
        }

}
